package com.stxx.assistant.framwork.job;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.stxx.assistant.domain.SysConfig;
import com.stxx.assistant.domain.SysTask;
import com.stxx.assistant.framwork.utils.StoreUtils;
import com.stxx.assistant.module.JobService;
import com.stxx.assistant.module.ffmpeg.VideoRecord;
import com.stxx.assistant.service.SysConfigService;
import com.stxx.assistant.service.SysTaskService;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.scheduling.annotation.Scheduled;

import java.sql.SQLException;
import java.util.*;

/**
 * @author Fuzhenlei
 * @date 2025/02/19 13:58
 */
@Component
public class TaskSechduler {
    @Inject
    SysTaskService taskService;
    @Inject
    SysConfigService configService;
    @Scheduled(fixedRate = 1000)
    public void task() throws SQLException {
        String worker = UUID.randomUUID().toString().replace("-", "");
        int rowCount = StoreUtils.sql("update sys_task set worker = ?,exec_time = ? where status = 0 and worker is null", worker, new Date()).update();
        if(rowCount==0)return;
        List<SysTask> tasks = StoreUtils.sql("select * from sys_task where worker = ?", worker).queryRowList(SysTask.class);
        for (SysTask task : tasks) {
            task.setStatus(2);
            try {
                JobService jobService = getJobService(task.getType());
                jobService.exec(task);
                task.setStatus(1);
                task.setRemark("执行成功");
            }catch (Exception e){
                task.setRemark(e.getMessage());
            }finally {
                HttpRequest request = HttpRequest.post(configService.config(SysConfigService.task_back_url,String.class));
                request.body(JSONUtil.createObj().set("success",task.getStatus()==1).set("message",task.getRemark()).set("attach", task.getAttach()).toString());
                try {
                    HttpResponse response = request.execute();
                    task.setBackStatus(2);
                    if(response.isOk()){
                        task.setBackStatus(1);
                    }
                }catch (Exception ex){
                    task.setRemark(task.getRemark()+";"+ex.getMessage());
                    ex.printStackTrace();
                }
                task.setFinishTime(new DateTime());
                taskService.update(task);
            }
        }
    }

    static Map<String,JobService> map = new HashMap<>();
    JobService getJobService(String type){
        if(map.containsKey(type)) {
            return map.get(type);
        }
        String packageStr = "com.stxx.assistant.module."+type;
        try {
            Class<?> clazz = Class.forName(packageStr);
            JobService jobService = (JobService)Solon.context().getBean(clazz);
            map.put(type,jobService);
            return jobService;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("任务类型"+type+"不正确");
        }
    }
}
